// src/renderer/App.tsx
import React, { useState, useMemo } from 'react';
import { Navigate, Route, Routes } from 'react-router-dom';
import { ConfigProvider, notification } from 'antd';
import zhCN from 'antd/locale/zh_CN';

import BaseHeader from './pages/layouts/BaseHeader';
import BaseSide from './pages/layouts/BaseSide';
import Operation from './pages/layouts/Operation';
import ServoDetail from './pages/ServoDetail';
import Home from './pages/Home';

import './App.css';

import {
  SerialContext,
  SerialState,
  GlobalModel,
  ServoModel,
} from './context/SerialContext';
import RouterInitializer from './pages/layouts/RouterInitializer';
import { Blockly } from './pages/Blockly';

// 自定义 hook 抽离 ipc 事件监听
function useIpcListeners(
  setSerialState: React.Dispatch<React.SetStateAction<SerialState>>,
  setServoModel: React.Dispatch<React.SetStateAction<ServoModel>>
) {
  React.useEffect(() => {
    const handleSerialError = (
      _event: any,
      _serialId: string,
      errorMessage: string
    ) => {
      notification.error({
        message: '串口错误',
        description: errorMessage,
        duration: 5,
      });
      setSerialState((prev) => ({ ...prev, isSerialOpen: false }));
    };

    const handleInsideError = (
      _event: any,
      _serialId: string,
      errorCode: number
    ) => {
      setServoModel((prev) => ({ ...prev, inside_error: errorCode }));
    };

    window.electron.ipcRenderer.on(
      'ipc-notification-receive-error',
      handleSerialError
    );
    window.electron.ipcRenderer.on(
      'ipc-notification-receive-inside-error',
      handleInsideError
    );

    return () => {
      window.electron.ipcRenderer.off(
        'ipc-notification-receive-error',
        handleSerialError
      );
      window.electron.ipcRenderer.off(
        'ipc-notification-receive-inside-error',
        handleInsideError
      );
    };
  }, [setSerialState, setServoModel]);
}

const App: React.FC = () => {
  const [serialState, setSerialState] = useState<SerialState>({
    isSerialOpen: false,
    isSerialSearch: false,
    isSerialUpgrade: false,
  });

  const [globalModel, setGlobalModel] = useState<GlobalModel>({
    global_serial_id: '',
  });

  const [servoModel, setServoModel] = useState<ServoModel>({
    inside_error: 0,
    servo_id: 0,
  });

  useIpcListeners(setSerialState, setServoModel);

  // 用 useMemo 避免 context value 频繁变化
  const contextValue = useMemo(
    () => ({
      serialState,
      setSerialState,
      globalModel,
      setGlobalModel,
      servoModel,
      setServoModel,
    }),
    [serialState, globalModel, servoModel]
  );

  return (
    <ConfigProvider locale={zhCN}>
      <SerialContext.Provider value={contextValue}>
        <RouterInitializer />
        <BaseHeader className="fixed-header" />
        <div className="main-container">
          <BaseSide className="side-menu-scrollable" />
          <div className="content-container">
            <Routes>
              <Route path="/" element={<Home />} />
              <Route path="/servo/:id" element={<ServoDetail />} />
              <Route path="/block" element={<Blockly />} />
            </Routes>
          </div>
        </div>
      </SerialContext.Provider>
    </ConfigProvider>
  );
};

export default App;
